package br.great.functionalCore;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import br.great.beans.Address;
import br.great.beans.Point;

/**
 * PhotoMap
 * Copyright (c) 2007-2008 STEAMER - LIG, All rights reserved.
 */
/**
 * @author Developpement of PhotoMap
 */
public class GeonamesAddress {

    private static String USER_AGENT = "geonames webservice client 0.5";
    private static String GEONAMES_SERVER = "http://ws.geonames.org";

    /** method description
     * @param var signification
     * @exception exception class name
     * @return return_value return signification
     * @see package.class#member label
     */
    public Address findAddress(Point point) {
        Address address = new Address();
        String url = GEONAMES_SERVER + "/findNearby?";
        url = url + "lat=" + point.getLatitude();
        url = url + "&lng=" + point.getLongitude();
        url = url + "&featureClass=P&featureCode=PPLA&featureCode=PPL&featureCode=PPLC";

//System.out.println(url);
        try {
            URLConnection conn = new URL(url).openConnection();
            conn.setRequestProperty("User-Agent", USER_AGENT);
            SAXBuilder parser = new SAXBuilder();
            Document doc = parser.build(conn.getInputStream());
            
            Element root = doc.getRootElement();
            Element codeElement = root.getChild("geoname");
            
            address.setNameCity(codeElement.getChildText("name"));
            address.setNameCountry(codeElement.getChildText("countryName"));

        } catch (JDOMException ex) {
            Logger.getLogger(GeonamesAddress.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GeonamesAddress.class.getName()).log(Level.SEVERE, null, ex);
        }
        return address;
    }
    
//    public static void main(String[] args){
//        GeonamesAddress ga = new GeonamesAddress();
//        Point point = new Point();
//        point.setLatitude(45);
//        point.setLongitude(12);
//        Address ad = ga.findAddress(point);
//        
//        System.out.println(ad.getNameCity());
//        System.out.println(ad.getNameCountry());
//    }
}
